<?php
/**
 * Created by PhpStorm.
 * User: panchaozhi
 * Date: 2016/7/12
 * Time: 13:05
 */

use app\models\User;
use yii\base\Model;
use Yii;

class SignupForm extends Model {

  public $username;
  public $email;
  public $password;
  public $password_compare;

  public function rules() {
    return [
      ['username', 'filter', 'filter'=>'trim'],
      ['username', 'required'],
      ['username', 'unique', 'targetClass'=>'\common\models/User', 'message'=>'用户名已经存在.'],
      ['username', 'string', 'min'=>2, 'max'=>255],

      ['email', 'filter', 'filter'=>'trim'],
      ['email', 'required'],
      ['email', 'email'],
      ['email', 'unique', 'targetClass'=>'common\models\User', 'message'=>'邮箱已经存在.'],

      [['password', 'password_compare'], 'required'],
      [['password', 'password_compare'], 'string', 'min'=>6, 'max'=>16, 'message'=>'{attribute}是6到16位的数字或字母.'],
      ['password_compare', 'compare', 'compareAttribute'=>'password', 'message'=>'两次的密码不一致.'],
    ];
  }

  public function signup() {
    if ($this->validate()) {
      $user = new User();
      $user->username = $this->username;
      $user->email = $this->email;
      $user->setPassword($this->password);
      $user->generateAuthKey();
      if ($user->save()) {
        return $user;
      }
    }
    return null;
  }
}